package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.util.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@RocketMQMessageListener(
        consumerGroup = MQConstants.SECKILL_ORDER_GROUP,
        topic = MQConstants.SECKILL_ORDER,
        selectorType = SelectorType.TAG,
        selectorExpression = MQConstants.SECKILL_CREATE_ORDER_TAG
)
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        Long seckillId = orderMessage.getSeckillId();
        Long userId = orderMessage.getUserId();
        String uuid = orderMessage.getUuid();

        Map<String, Object> map = new HashMap<>();
        map.put("seckillId", seckillId);
        map.put("uuid", uuid);
        map.put("userId", userId);
        try {
            String orderNo = orderInfoService.doSeckill(userId, seckillId);
            map.put("data", orderNo);
            map.put("code", 200);
            rocketMQTemplate.syncSend(MQConstants.SECKILL_CREATE_SUCCESS_DEST, map);
        } catch (Exception e) {
            map.put("code", SeckillCodeMsg.SECKILL_ORDER_FAIL.getCode());
            map.put("msg", SeckillCodeMsg.SECKILL_ORDER_FAIL.getMsg());
            rocketMQTemplate.syncSend(MQConstants.SECKILL_CREATE_FAIL_DEST, map);
            e.printStackTrace();
        }
    }
}
